'use strict';
const urlJoin = require('url-join');
const axios = require('axios');
const semver = require('semver');

module.exports = {
  getNpmInfo,
  getDefaultRegistryUrl,
  getNpmVersions,
  getOnLineLatestVersion,
  getNpmLatestVersion
};

function getNpmInfo(packageName, registry) {
  if(!packageName) return null;
  const registryUrl = registry || getDefaultRegistryUrl();
  const npmInfoUrl = urlJoin(registryUrl,packageName);
  return axios.get(npmInfoUrl).then((result) => {
    if(result.status === 200) {
      return result.data;
    } else {
      return null;
    }
  }).catch((err) => {
    throw new Error(err);
  });
  
}

function getDefaultRegistryUrl(isOrigin=true) {
  return isOrigin ?  'https://registry.npmjs.org' : 'https://registry.npmmirror.com'
}

async function getNpmVersions(packageName, registry) {
  const data = await getNpmInfo(packageName, registry);
  if(data) {
    return Object.keys(data.versions);
  } else {
    return []
  }
}

function getSemverVersions(baseVersion, versions) {
  return versions
          .filter(version => semver.satisfies(version, `^${baseVersion}`))
          .sort((a, b)=>semver.gt(b, a) ? 1 : -1)
  }

// 以3.x.x 同层的版本
 async function getOnLineLatestVersion(baseVersion, packageName, registry) {
  const version = await getNpmVersions(packageName, registry)
  const newVersions = getSemverVersions(baseVersion, version)
  
  if(newVersions && newVersions.length > 0) {
    return newVersions[0]
  }
}

async function getNpmLatestVersion(npmName, registry) {
  const versions = await getNpmVersions(npmName, registry)
  if(versions && versions.length > 0) {
   return versions.sort((a, b) => semver.gt(b, a) ? 1 : -1)[0]
  }
  return null
}